import requests
import json
import hashlib
import time


class SendCode:

    def send(self, account, pswd, mobile, msg, ts, state):
        url = 'http://139.196.108.241:8080' + {
            1: '/Api/HttpSendSMYzm.ashx',
            2: '/Api/HttpSendSMYx.ashx',
            3: '/Api/HttpSendSMVoice.ashx'
        }[state]
        if ts != "":
            m = hashlib.md5()
            strs = account + pswd + str(ts)
            m.update(strs.encode("utf8"))
            pswd = m.hexdigest()
        body = {"account": account, "pswd": pswd, "mobile": mobile, "msg": msg, "ts": str(ts)}

        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                       "Content-Type": "application/x-www-form-urlencoded"}

        response = requests.post(url, data=body, headers=header_dict)

        return json.loads(response.text)


# 单例设计模式
class CCP(object):
    """发送验证码的单例类"""

    # __new__是在实例创建之前被调用的，因为它的任务就是创建实例然后返回该实例对象，是个静态方法。
    def __new__(cls, *args, **kwargs):
        """
        定义单例的初始化方法
        :return ：单例
        """
        # 判断单例是否存在
        # hasattr()判断一个对象里面是否有name属性或者name方法，返回BOOL值，有name特性返回True， 否则返回False。
        if not hasattr(cls, '_instance'):  # _instance属性中存储的就是单例
            # 单例如果不存在，初始化单例
            cls._instance = super(CCP, cls).__new__(cls, *args, **kwargs)

            # 初始化 REST SDK
            cls._instance.send = SendCode()

        # 返回单例
        return cls._instance

    def send_template_sms(self, account, pswd, mobile, msg):
        """
        发送短信验证码单例方法
        :param account:用户账号
        :param pswd:用户密码
        :param mobile:合法的手机号码
        :param msg:短信内容
        :return:
        """
        # print(res['result'])
        result = self.send.send(account, pswd, mobile, msg, (int(time.time())), 1)
        # print(result)
        # if result['result'] == "0":  # 成功返回0
        #     return 0
        # else:
        #     return -1  # 失败返回1
        return 0


if __name__ == '__main__':
    # 单例类发送短信验证码
    CCP().send_template_sms("18791957243", "wei990319.", "18791957243", "您的验证码是{$var}，如非本人操作，请忽略本短信！")
